import React, {
  useState,
  useEffect,
  useCallback,
  forwardRef,
  useImperativeHandle,
} from "react";
import { Space, Dropdown } from "antd";
import SearchTagSelect from "../SearchTagSelect";
import SearchResults from "../SearchResults";
import SearchTreeResults from "../SearchTreeResults";
import teamService, {
  flattenOrganizationTreeData,
} from "../../services/teamService";
import UserAvatarWithName from "../../components/UserAvatarWithName";

import { PaginationParams } from "../../types/api";
import type { User, Organization } from "../../types/user";
import type { TreeDataNode } from "../../types/tree";

interface TeamMemberSelectorProps {
  onChange?: (selectedItems: User[]) => void;
  existingSelectedItems?: User[];
}

export interface TeamMemberSelectorRef {
  clearSelectedItems: () => void;
}

const TeamMemberSelector = forwardRef<
  TeamMemberSelectorRef,
  TeamMemberSelectorProps
>(({ onChange, existingSelectedItems = [] }, ref) => {
  const [searchText, setSearchText] = useState("");
  const [loading, setLoading] = useState(false);
  const [filteredOptions, setFilteredOptions] = useState<User[]>([]);
  const [showSearchResults, setShowSearchResults] = useState(false);
  const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const [page, setPage] = useState(1);
  const [pageSize] = useState(10);

  const [hasMore, setHasMore] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);

  const [selectedItems, setSelectedItems] = useState<User[]>([]);

  // 原始树数据
  const [originalTreeData, setOriginalTreeData] = useState<Organization[]>([]);
  useEffect(() => {
    fetchOrganizationTree();
  }, []);

  // 暴露给外部的清除方法
  useImperativeHandle(ref, () => ({
    clearSelectedItems: () => {
      setSelectedItems([]);
      setSearchText("");
      setShowSearchResults(false);
      setDropdownOpen(false);
    },
  }));

  // 接口获取组织架构树
  const fetchOrganizationTree = async () => {
    try {
      let response = await teamService.getOrganizationTree();

      // response 如果是对象转数组
      if (response && !Array.isArray(response)) {
        response = [response];
      }

      setOriginalTreeData(response); // 保存原始树数据
      const processInitialData = (data: any[]): TreeDataNode[] => {
        return data.map((item) => {
          delete item.children; // 删除 children 属性
          return {
            key: item.orgId || -999,
            title: item.name,
            isLeaf: false,
            data: item,
            isOrg: true,
          };
        });
      };
      setTreeData(processInitialData(JSON.parse(JSON.stringify(response)))); // 深拷贝赋值
    } catch (error) {
      console.error("Failed to fetch organization tree data:", error);
    }
  };

  // 接口查询 teamService.getUsers
  const fetchSearchResults = async (params: PaginationParams) => {
    try {
      const { users } = await teamService.getUsers(params); // 调用接口获取用户数据
      const processedResults = users.map((item: User) => ({ ...item }));
      return processedResults;
    } catch (error) {
      console.error("Failed to fetch search results:", error);
      return [];
    }
  };

  const handleSearch = async (value: string) => {
    setSearchText(value);
    setDropdownOpen(true);
    setPage(1);
    setHasMore(true);

    if (!value) {
      setShowSearchResults(false);
      setFilteredOptions([]);
      return;
    }

    setLoading(true);
    setShowSearchResults(true);

    try {
      const results = await fetchSearchResults({
        keyword: value,
        page_num: 1,
        page_size: pageSize,
      });
      setFilteredOptions(results);
      setHasMore(results.length === pageSize); // 判断是否还有更多数据
    } catch (error) {
      console.error("Failed to fetch search results:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleLoadMore = useCallback(async () => {
    if (loadingMore || !hasMore || !searchText) return;

    setLoadingMore(true);
    const nextPage = page + 1;

    try {
      const results = await fetchSearchResults({
        keyword: searchText,
        page_num: nextPage,
        page_size: pageSize,
      });
      setFilteredOptions((prev) => [...prev, ...results]);
      setHasMore(results.length === pageSize); // 判断是否还有更多数据
      setPage(nextPage);
    } catch (error) {
      console.error("Failed to load more search results:", error);
    } finally {
      setLoadingMore(false);
    }
  }, [loadingMore, hasMore, searchText, page, pageSize]);

  // 多选操作处理
  const handleConfirm = (selectedOptions: User[]) => {
    handleSelectedOptionsChange(selectedOptions);
    setSearchText("");
    setShowSearchResults(false);
    setDropdownOpen(false);
  };

  // 更新selectedOptions id相同的去重剩下的合并
  const handleSelectedOptionsChange = (newSelectedOptions: User[]) => {
    const uniqueOptions = Array.from(
      new Map(newSelectedOptions.map((option) => [option.id, option])).values()
    );
    setSelectedItems(uniqueOptions);
    debugger;
    onChange?.(uniqueOptions); // 调用外部传入的 onConfirm 函数
  };

  const handleCancel = () => {
    setShowSearchResults(false);
    setDropdownOpen(false);
  };

  const handleLoadData = (node: TreeDataNode): Promise<TreeDataNode[]> => {
    console.log("handleLoadData", treeData); // 调试输出

    const { key, children, data } = node;

    if (
      (children && children.length > 0) ||
      !key ||
      node.isLeaf === true ||
      data?.type === "member"
    ) {
      return Promise.resolve<TreeDataNode[]>([]);
    }

    return new Promise<TreeDataNode[]>((resolve) => {
      const nodeType = node?.data?.type || "department";
      const parentKey = node?.key || -999;
      // flattenOrganizationTreeData
      if (nodeType === "department") {
        teamService
          .getOrganizationTreeById(
            parentKey,
            flattenOrganizationTreeData(originalTreeData)
          )
          .then((departmentChildren) => {
            // departmentChildren 如果是对象转数组
            if (departmentChildren && !Array.isArray(departmentChildren)) {
              departmentChildren = [departmentChildren];
            }

            // 处理获取到的部门数据
            const processedChildren = departmentChildren.map((item) => {
              const { name, id, isOrg } = item;
              const nodeKey = id || -999;
              const nodeData = item;

              const title = isOrg ? (
                name
              ) : (
                <UserAvatarWithName
                  key={nodeData.id}
                  name={nodeData.name}
                  avatar={nodeData.avatar}
                  subtitle={nodeData.empAccount}
                  size="small"
                  shape="circle"
                />
              );
              return {
                key: nodeKey,
                title,
                isLeaf: !isOrg,
                data: nodeData,
              };
            });
            resolve(processedChildren);
          })
          .catch((error) => {
            console.error("Failed to load data:", error);
            resolve([]); // 处理错误情况
          });
      } else {
        resolve([]);
      }
    });
  };

  const fetchCondition = (checkedKeys: any) => {
    return new Promise((resolve) => {
      teamService
        .getOrganizationTreeByOrgPath(checkedKeys)
        .then((res) => {
          resolve(res);
        })
        .catch((error) => {
          console.error("Failed to fetch organization tree data:", error);
          resolve([]); // 处理错误情况
        });
    });
  };

  // const test = () => {
  //   console.log("existingSelectedItems", existingSelectedItems); // 调试输出
  //   console.log("selectedItems", selectedItems); // 调试输出
  //   console.log("selectedValues", selectedValues); // 调试输出
  //   console.log("filteredOptions", filteredOptions); // 调试输出
  //   console.log("treeData", treeData); // 调试输出
  // };
  const dropdownContent = (
    <div
      style={{
        backgroundColor: "#fff",
        boxShadow: "0 3px 6px rgba(0,0,0,0.1)",
        borderRadius: "4px",
        minWidth: "100%",
      }}
    >
      {searchText ? (
        <SearchResults
          visible={showSearchResults}
          loading={loading}
          options={filteredOptions}
          onConfirm={handleConfirm}
          onCancel={handleCancel}
          selectedItems={selectedItems}
          existingSelectedItems={existingSelectedItems}
          usePagination={true}
          hasMore={hasMore}
          loadingMore={loadingMore}
          onLoadMore={handleLoadMore}
          style={{ position: "static", boxShadow: "none", margin: 0 }}
          renderOption={(member) => (
            <UserAvatarWithName
              key={member.id}
              name={member.name}
              avatar={member.avatar}
              subtitle={member.orgName}
              description={member.empAccount}
              displayType="vertical"
            />
          )}
        />
      ) : (
        <SearchTreeResults
          fetchCondition={fetchCondition as any}
          treeData={treeData}
          selectedItems={selectedItems}
          existingSelectedItems={existingSelectedItems}
          onConfirm={handleConfirm}
          onCancel={handleCancel}
          loadData={handleLoadData}
        />
      )}
    </div>
  );

  return (
    <Space direction="vertical" style={{ width: "100%" }}>
      <div style={{ position: "relative" }}>
        <Dropdown
          open={dropdownOpen}
          onOpenChange={setDropdownOpen}
          dropdownRender={() => dropdownContent}
          trigger={["click"]}
          placement="bottomLeft"
          getPopupContainer={(triggerNode) =>
            triggerNode.parentElement || document.body
          }
          overlayStyle={{ width: "100%" }}
        >
          <div onClick={() => setDropdownOpen(true)}>
            <SearchTagSelect
              disabledRemove={dropdownOpen}
              selectedOptions={selectedItems}
              onChange={handleSelectedOptionsChange}
              onSearch={handleSearch}
              placeholder="搜索人员姓名"
              searchValue={searchText}
              renderTag={(member) => (
                <UserAvatarWithName
                  key={member.id}
                  name={member.name}
                  avatar={member.avatar}
                  size="small"
                  shape="circle"
                />
              )}
            />
          </div>
        </Dropdown>
      </div>
    </Space>
  );
});

export default TeamMemberSelector;
